//
//  YMPDFLoader.m
//  TestDemo
//
//  Created by fengxijun on 16/6/23.
//  Copyright © 2016年 goappbox. All rights reserved.
//

#import "YMPDFLoader.h"
#import "YMFileCacheManager.h"

@implementation YMPDFLoader

- (void) loadContentWithUrl:(NSURL *)url {
    if ([url isFileURL]) {
        [self loadPdfFile:[url path]];
    } else {
        // 先获取文档再解析。
    }
}

- (BOOL)isPDF:(NSString *)filePath
{
    BOOL state = NO;
    
    if (filePath != nil) // Must have a file path
    {
        const char *path = [filePath fileSystemRepresentation];
        
        int fd = open(path, O_RDONLY); // Open the file
        
        if (fd > 0) // We have a valid file descriptor
        {
            const char sig[1024]; // File signature buffer
            
            ssize_t len = read(fd, (void *)&sig, sizeof(sig));
            
            state = (strnstr(sig, "%PDF", len) != NULL);
            
            close(fd); // Close the file
        }
    }
    
    return state;
}

- (void) loadPdfFile:(NSString *)filepath {
    if (![[NSFileManager defaultManager] fileExistsAtPath:filepath]) {
        if (self.fileLoadStatus) {
            self.fileLoadStatus(YMFileNotExists);
        }
        return;
    }
    
    if (![self isPDF:filepath]) {
        if (self.fileLoadStatus) {
            self.fileLoadStatus(YMNotPDF);
        }
        return;
    }
    
    NSError *error = nil;
    _pdfDoc = [[YMPDFDocument alloc] initWithfilepath:filepath
                                             passowrd:nil
                                                error:&error];
    if (error) {
        if (self.fileLoadStatus) {
            self.fileLoadStatus([[error userInfo][errorCodeKey] unsignedIntegerValue]);
        }
    } else {
        if (self.fileLoadStatus) {
            self.fileLoadStatus(YMPDFOpenSuccess);
        }
    }
}

@end
